﻿using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.ServiceModel.DomainServices.Client;
using AstekServis.Web.Data;
using System.Linq;

namespace AstekServis.Views
{
    public partial class ParcaPaketTanitim : ChildWindow
    {
        List<PaketSatir> _lines = new List<PaketSatir>();
        AsTekDomainContext context = new AsTekDomainContext();
        List<Doviz> _dovizler = new List<Doviz>();

        public ParcaPaketTanitim()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(ParcaPaketTanitim_Loaded);
        }

        void ParcaPaketTanitim_Loaded(object sender, RoutedEventArgs e)
        {
            agDataGrid1.AddColumn("ParcaAdi");
            agDataGrid1.AddColumn("Fiyati");
            agDataGrid1.AddColumn("Doviz");
            agDataGrid1.DataSource = _lines;
            agDataGrid1.Columns[0].MinColumnWidth = 300;
            LoadDoviz();
        }

        private void LoadDoviz()
        {
            EntityQuery<Doviz> qry = context.GetDovizlerQuery();
            LoadOperation<Doviz> operation = context.Load(qry);
            operation.Completed += (ss, oo) =>
            {
                LoadOperation<Doviz> op = ss as LoadOperation<Doviz>;
                if (op.HasError)
                {
                    System.Windows.MessageBox.Show(op.Error.ToString(), "Load Error",
                    System.Windows.MessageBoxButton.OK);
                    op.MarkErrorAsHandled();
                }
                else
                {
                    _dovizler.AddRange(op.Entities.ToArray());
                    cmbDoviz.ItemsSource = op.Entities;
                    cmbDoviz.DisplayMemberPath = "Adi";
                    if (cmbDoviz.Items.Count > 0)
                        cmbDoviz.SelectedIndex = 0;
                }
            };
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            Save();
        }

        private void yeniEvrak()
        {
            yeni();
            txtAciklama.Text = "";
            txtStokKodu.Text = "";
            txtStokKodu.Tag = null;
            _lines.Clear();
            agDataGrid1.Refresh();
        }

        private void Save()
        {
            LoadOperation<ParcaTanim> operation = context.Load(context.GetParcaTanimlariQuery().Where(x => x.AnaUrunKodu == txtStokKodu.Tag.ToString()));
            operation.Completed += (ss, oo) =>
            {
                LoadOperation<ParcaTanim> op = ss as LoadOperation<ParcaTanim>;
                if (op.HasError)
                {
                    System.Windows.MessageBox.Show(op.Error.ToString(), "Load Error",
                    System.Windows.MessageBoxButton.OK);
                    op.MarkErrorAsHandled();
                }
                else
                {
                    List<ParcaTanim> liste = op.Entities.ToList();
                    if (liste.Count > 0)
                    {
                        foreach (var item in liste)
                        {
                            context.ParcaTanims.Remove(item);
                        }
                    }

                    ParcaTanim p;
                    foreach (var item in _lines)
                    {
                        p = new ParcaTanim();
                        p.Aciklamasi = txtAciklama.Text;
                        p.AnaUrunKodu = txtStokKodu.Tag.ToString();
                        p.DovizCins = Cevir.Parse<byte>(item.DovizID);
                        p.HizmetKodu = item.HizmetKodu;
                        p.ParcaAdi = item.ParcaAdi;
                        p.ParcaFiyati = item.Fiyati;
                        context.ParcaTanims.Add(p);
                    }

                    context.SubmitChanges(so =>
                    {
                        if (so.HasError)
                            MessageBox.Show("Hata:\r\n" + so.Error.Message);
                        else
                        {
                            MessageBox.Show("Kaydedildi !");
                            yeniEvrak();
                        }
                    }, null);
                }
            };
        }

        private void Delete()
        {
            LoadOperation<ParcaTanim> operation = context.Load(context.GetParcaTanimlariQuery().Where(x => x.AnaUrunKodu == txtStokKodu.Tag.ToString()));
            operation.Completed += (ss, oo) =>
            {
                LoadOperation<ParcaTanim> op = ss as LoadOperation<ParcaTanim>;
                if (op.HasError)
                {
                    System.Windows.MessageBox.Show(op.Error.ToString(), "Load Error",
                    System.Windows.MessageBoxButton.OK);
                    op.MarkErrorAsHandled();
                }
                else
                {
                    List<ParcaTanim> liste = op.Entities.ToList();
                    if (liste.Count > 0)
                    {
                        foreach (var item in liste)
                        {
                            context.ParcaTanims.Remove(item);
                        }
                    }

                    context.SubmitChanges(so =>
                    {
                        if (so.HasError)
                            MessageBox.Show("Hata:\r\n" + so.Error.Message);
                        else
                        {
                            MessageBox.Show("Silindi !");
                            yeniEvrak();
                        }
                    }, null);
                }
            };
        }

        private void Load()
        {
            LoadOperation<ParcaTanim> operation = context.Load(context.GetParcaTanimlariQuery().Where(x => x.AnaUrunKodu == txtStokKodu.Tag.ToString()));
            operation.Completed += (ss, oo) =>
            {
                LoadOperation<ParcaTanim> op = ss as LoadOperation<ParcaTanim>;
                if (op.HasError)
                {
                    System.Windows.MessageBox.Show(op.Error.ToString(), "Load Error",
                    System.Windows.MessageBoxButton.OK);
                    op.MarkErrorAsHandled();
                }
                else
                {
                    List<ParcaTanim> liste = op.Entities.ToList();
                    if (liste.Count > 0)
                    {
                        txtAciklama.Text = liste[0].Aciklamasi;
                        foreach (var item in liste)
                        {
                            _lines.Add(new PaketSatir()
                            {
                                Doviz = _dovizler.Where(x => x.id == item.DovizCins).Select(x => x.Adi).FirstOrDefault(),
                                DovizID = item.DovizCins,
                                Fiyati = item.ParcaFiyati,
                                HizmetKodu = item.HizmetKodu,
                                ParcaAdi = item.ParcaAdi
                            });
                        }
                        agDataGrid1.Refresh();
                    }
                }
            };
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void btnListe_Click(object sender, RoutedEventArgs e)
        {
            yeniEvrak();
            AracListesi liste = new AracListesi();
            liste.Filtre = txtStokKodu.Text;
            liste.ListeTipi = AracListesi.ListeTipleri.Stok;
            liste.Show();
            liste.Closed += (s, o) =>
            {
                AracListesi frm = (AracListesi)s;
                if (frm.DialogResult.HasValue && frm.DialogResult.Value)
                {
                    txtStokKodu.Text = frm.SecilenStok.Adi;
                    txtStokKodu.Tag = frm.SecilenStok.Kodu;
                    Load();
                }
            };
        }

        private void btnEkle_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(txtParcaAdi.Text) && !string.IsNullOrEmpty(txtFiyati.Text) && !string.IsNullOrEmpty(txtHizmetKodu.Text) && cmbDoviz.SelectedIndex > -1)
            {
                _lines.Add(new PaketSatir()
                {
                    Doviz = ((Doviz)cmbDoviz.SelectedItem).Adi,
                    DovizID = Cevir.Parse<byte>(((Doviz)cmbDoviz.SelectedItem).id),
                    Fiyati = Cevir.Parse<double>(txtFiyati.Text),
                    HizmetKodu = txtHizmetKodu.Text,
                    ParcaAdi = txtParcaAdi.Text
                });
                agDataGrid1.Refresh();
                yeni();
            }
            else
            {
                MessageBox.Show("Lütfen bilgileri eksiksiz girin !");
            }
        }

        private void yeni()
        {
            txtParcaAdi.Text = "";
            txtFiyati.Text = "";
            txtHizmetKodu.Text = "";
            cmbDoviz.SelectedIndex = 0;
        }

        private void btnCikar_Click(object sender, RoutedEventArgs e)
        {
            if (agDataGrid1.FocusedRowHandle > -1)
            {
                _lines.RemoveAt(agDataGrid1.FocusedRowHandle);
                agDataGrid1.Refresh();
                yeni();
            }
        }

        private void btnYeni_Click(object sender, RoutedEventArgs e)
        {
            yeni();
        }

        private void btnSil_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(txtStokKodu.Text))
            {
                Delete();
            }
        }
    }
}

